package light.head.dao.el;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.el.TrainData;
@Service
public class TrainDataDAO extends BaseDAO<TrainData, Integer>{
	
	public RESULT findByMap(Integer oc, Map<String, String> map, PageBean pageBean){
		if(oc == null) return null;
		List<Object> list = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer("FROM TrainData tm WHERE tm.oc = ?");
		list.add(oc);
		
		if(map != null){
			String name = map.get(Parm.NAME);
			String deleted = map.get(Parm.DELETED);
			String isPublic = map.get("isPublic");
			String cc = map.get(Parm.CC);
			
			if(isNotNull(name)){
				sql.append(" AND tm.name LIKE ?");
				list.add("%" + name + "%");
			}
			if(isNotNull(cc)){
				sql.append(" AND tm.code IN(SELECT cmr.tdc FROM CourseDataRelation cmr WHERE cmr.tdc = ?)");
				list.add(Integer.parseInt(cc));
			}
			if(isNotNull(isPublic)){
				sql.append(" AND tm.isPublic = ?");
				list.add(Boolean.parseBoolean(isPublic));
			}
			if(isNotNull(deleted)){
				sql.append(" AND tm.deleted = ?");
				list.add(Boolean.parseBoolean(deleted));
			}
			
		}
		
		sql.append(" ORDER BY tm.code DESC");
		return findToPageBean(sql.toString(), pageBean, list);
	}
	
	
	public RESULT update(TrainData tm){
		if(tm == null || tm.getCode() == null) return RESULT.ERROR;
		
		TrainData old = get(tm.getCode());
		
		if(old == null) return RESULT.NOT_FIND;
		
		if(isNotNull(tm.getName())){
			old.setName(tm.getName());
		}
		if(tm.getIsPublic() != null && tm.getIsPublic() != old.getIsPublic()){
			old.setIsPublic(tm.getIsPublic());
		}
		old.setContent(tm.getContent());
		old.setRemark(tm.getRemark());
		old.setUrl(tm.getUrl());
		
		return upd(old);
	}
	
	/**
	 * 根据课程编号获取所属资料
	 */
	 public List<TrainData> findByCc(Integer cc){
		 String sql = "FROM TrainData tm WHERE tm.code IN(SELECT cmr.tdc FROM CourseDataRelation cmr WHERE cmr.cc = ?)";
		 return find(sql, cc);
	 }
}
